const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');

const User = require('../../app/models/User');
const Role = require('../../app/models/Role');

passport.serializeUser((user, done) => {
    done(null, user.id)
});
passport.deserializeUser((name, done) => {
    User.findOne(name, (err, user) => {
        done(err, user)
    })
})

passport.use(new LocalStrategy(
    {usernameField: 'name'},
    async (name, password, done) => {
        let include = [{
            model: Role
        }];
        let user = await User.findOne({ attributes: { exclude: ['ip', 'role_id', 'updated_at'] }, where: { name }, include })
        if(!user) return done(false, {message: '账号或密码错误..'})

        bcrypt.compare(password, user.password, (err, isMatch) => {
            if(err) throw err;
            if(isMatch) {
                delete user.dataValues['password'];
                return done(user);
            }else{
                return done(false, {message: '账号或密码错误.'})
            }
        })
    }
));

module.exports = passport;
